package com.woniuxy.courseservice.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.core.model.Result;
import com.woniuxy.core.status.CourseState;
import com.woniuxy.core.util.PageInfo;
import com.woniuxy.courseclient.client.ProductFeignClient;
import com.woniuxy.courseclient.client.VenueFeignClient;
import com.woniuxy.courseclient.client.dto.TeamProductDto;
import com.woniuxy.coursedao.mapper.TeamCourseMapper;
import com.woniuxy.coursedao.model.TeamCourse;
import com.woniuxy.coursemodel.param.OneTeamCourseParam;
import com.woniuxy.coursemodel.param.ScheduleParam;
import com.woniuxy.coursemodel.param.TeamCoursePageParam;
import com.woniuxy.courseservice.service.TeamCourseService;
import com.woniuxy.courseservice.service.exception.OrdinaryCourseException;
import com.woniuxy.courseservice.service.exception.TeamCourseException;
import org.springframework.boot.ansi.AnsiOutput;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 团课课程表 服务实现类
 * </p>
 *
 * @author 冉杰
 * @since 2024-01-15
 */
@Service
public class TeamCourseServiceImpl extends ServiceImpl<TeamCourseMapper, TeamCourse> implements TeamCourseService {

    @Resource
    private ProductFeignClient productFeignClient;
    @Resource
    private VenueFeignClient venueFeignClient;
    @Resource
    private TeamCourseMapper teamCourseMapper;

    @Override
    @Transactional
    public void schedule(ScheduleParam param) {
        Result<TeamProductDto> result = productFeignClient.findTeamProductById(param.getTeamProductId());
        if (!result.getFlag()) throw new TeamCourseException(result.getCode(), result.getMsg());
        if (BeanUtil.isEmpty(result.getData())) throw new TeamCourseException(6008,"该团课课程产品不存在");
        TeamProductDto dto = result.getData();
        if (dto.getVenueId().intValue() != param.getVenueId().intValue())
            throw new TeamCourseException(6004, "只能对自己场馆的产品进行排课");
        // 将字符串转换为 Date 对象
        Date date = DateUtil.parse(param.getDay()).toJdkDate();
        // 将 Date 对象转换为 LocalDate 对象
        LocalDate localDate = date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
        ArrayList<TeamCourse> list = new ArrayList<>();
        for (int i = 0; i < dto.getCourseCount(); i++) {

            String startTime = localDate.plusDays(i) + " " + param.getTime();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            // 将字符串解析为 LocalDateTime 对象
            LocalDateTime dateTime = LocalDateTime.parse(startTime, formatter);
            // 加上两个小时
            LocalDateTime addedTime = dateTime.plusHours(2);
            // 将结果转换为字符串
            String endTime = addedTime.format(formatter);
            TeamCourse teamCourse = new TeamCourse();
            teamCourse.setTeamProductId(dto.getTeamProductId());
            teamCourse.setTeamProductName(dto.getTeamProductName());
            teamCourse.setVenueId(dto.getVenueId());
            teamCourse.setCoachId(dto.getCoachId());
            teamCourse.setStartTime(startTime);
            teamCourse.setEndTime(endTime);
            teamCourse.setTeamCourseState(CourseState.IS_OPEN.getState());
            LambdaQueryWrapper<TeamCourse> wrapper = new LambdaQueryWrapper<>();
            wrapper.between(TeamCourse::getStartTime, startTime, endTime);
            long count = count(wrapper);
            if (count!=0) throw new TeamCourseException(6020,startTime+"到"+endTime+"时间内已有团课课程安排");
            list.add(teamCourse);
        }
        saveBatch(list);
    }

    @Override
    @Transactional
    public void del(Integer teamProductId, Integer venueId) {
        LambdaQueryWrapper<TeamCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TeamCourse::getTeamProductId,teamProductId);
        List<TeamCourse> courses = list(wrapper);
        for (TeamCourse teamCourse : courses) {
            teamCourse.setTeamCourseState(CourseState.IS_DISABLED.getState());
            if (teamCourse.getTeamCourseState().intValue()==CourseState.IS_OPEN.getState())
                throw new TeamCourseException(6006,"部分课程开课状态中不能进行删除");
            if (teamCourse.getVenueId().intValue()!=venueId)
                throw new TeamCourseException(6007,"只能对自己场馆下的课程进行删除操作");
        }
        System.out.println(courses);
        removeBatchByIds(courses);
    }

    @Override
    public PageInfo<TeamCourse> byPage(TeamCoursePageParam param) {
        LambdaQueryWrapper<TeamCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TeamCourse::getVenueId,param.getVenueId()).eq(TeamCourse::getTeamProductId,param.getTeamProductId())
                .ge(TeamCourse::getStartTime, LocalDate.now()).orderByDesc(TeamCourse::getStartTime);
        Page<TeamCourse> page = new Page<>(param.getPageNum(), param.getPageSize());
        page(page,wrapper);
        PageInfo<TeamCourse> pageInfo = BeanUtil.toBean(page, PageInfo.class);
        pageInfo.setPages(page.getPages());
        pageInfo.setList(page.getRecords());
        return pageInfo;
    }

    @Override
    @Transactional
    public void delByIds(List<Integer> teamCourseIds, Integer venueId) {
        LambdaQueryWrapper<TeamCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(TeamCourse::getTeamCourseId,teamCourseIds);
        List<TeamCourse> teamCourses = teamCourseMapper.selectList(wrapper);
        for (TeamCourse teamCourse : teamCourses) {
            teamCourse.setTeamCourseState(CourseState.IS_DISABLED.getState());
            if (teamCourse.getTeamCourseState().intValue()==CourseState.IS_OPEN.getState())
                throw new TeamCourseException(6006,"部分课程开课状态中不能进行删除");
            if (teamCourse.getVenueId().intValue()!=venueId)
                throw new TeamCourseException(6007,"只能对自己场馆下的课程进行删除操作");
        }
        removeBatchByIds(teamCourses);
    }

    @Override
    public void one(OneTeamCourseParam param) {
        Result<TeamProductDto> productDtoResult = productFeignClient.findTeamProductById(param.getTeamProductId());
        if (!productDtoResult.getFlag()) throw new
                TeamCourseException(productDtoResult.getCode(), productDtoResult.getMsg());
        if (BeanUtil.isEmpty(productDtoResult.getData())) throw new TeamCourseException(6008,"该团课课程产品不存在");
        TeamProductDto dto = productDtoResult.getData();
        if (dto.getVenueId().intValue() != param.getVenueId().intValue())
            throw new TeamCourseException(6004, "只能对自己场馆的产品进行排课");
        LambdaQueryWrapper<TeamCourse> wrapper = new LambdaQueryWrapper<>();
        wrapper.between(TeamCourse::getStartTime, param.getStartTime(), param.getEndTime());
        long count = count(wrapper);
        if (count!=0) throw new TeamCourseException(6020,"该时间内已有团课课程安排");
        TeamCourse teamCourse = BeanUtil.toBean(param, TeamCourse.class);
        teamCourse.setTeamProductName(dto.getTeamProductName());
        teamCourse.setCoachId(dto.getCoachId());
        teamCourse.setTeamCourseState(CourseState.IS_OPEN.getState());
        save(teamCourse);
    }
}
